<template>
  <div class="sys-org-container">
    <el-dialog v-model="state.isShowDialog" draggable :close-on-click-modal="false" width="40%">
      <template #header>
        <div style="color: #fff">
          <el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle">
            <ele-Edit />
          </el-icon>
          <span> {{ props.title }} </span>
        </div>
      </template>

      <el-tabs v-model="state.first" :tab-position="tabPosition" class="demo-tabs"
        style="position: relative;" @tab-click="handleTab">
        <el-tab-pane label="修改在库时间(h)" name="tabOne">
          <el-radio-group v-model="state.isChecked" class="ml-4" @change="handleChange">
            <el-radio :label="true" size="large">设置预警时间</el-radio>
            <el-radio :label="false" size="large">不设置预警时间</el-radio>
          </el-radio-group>
          <el-form ref="Timeref" :model="state.TimeruleForm" :rules="state.rules" v-if="state.isChecked">

            <el-form-item prop="ControlTime">
              <el-input width="70" v-model="state.TimeruleForm.ControlTime" placeholder="请输入在库控制时间" />
            </el-form-item>
          </el-form>
          <span v-if="state.valid">请输入正确的数字时间格式</span>
        </el-tab-pane>
        <el-tab-pane label="修改安全库存" name="tabTwo">
          <el-radio-group v-model="state.isCheckedSafe" class="ml-4" @change="handleChangeSafe">
            <el-radio :label="true" size="large">设置安全库存</el-radio>
            <el-radio :label="false" size="large">不设置安全库存</el-radio>
          </el-radio-group>
          <el-form ref="Saferef" :model="state.SaferuleForm" v-if="state.isCheckedSafe" :rules="state.rules">
            <el-form-item prop="safeStock">
              <el-input width="70" v-model="state.SaferuleForm.safeStock" placeholder="请输入安全库存" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="sysEditOrg">
  import { onMounted, reactive, ref } from "vue";
  import {ElMessage } from "element-plus";

  import { WmsApi } from "/@/api/wh";

  const props = defineProps({
    title: String,
  });
  const tabPosition = ref("left");
  const emits = defineEmits(["handleQuery"]);

  const Saferef = ref();
  //在库时间控制表单的ref
  const Timeref = ref();
  const state = reactive({
    isChecked: false,
    isCheckedSafe: false,
    SaferuleForm: {
      safeStock: "",
    },
    TimeruleForm: {
      ControlTime: "",
    },
    isShowDialog: false,
    ruleForm: {},
    materielWorkBins: [],
    num: "",
    first: "tabOne",
    rules: {
      ControlTime: [
        { required: true, message: "在库控制时间不能为空", trigger: "blur" },
        { pattern: /^[0-9]+$/, message: '只能输入数字', trigger: 'blur' }
      ],
      safeStock: [{ required: true, message: "安全库存不能为空", trigger: "blur" },
      { pattern: /^[0-9]+$/, message: '只能输入数字', trigger: 'blur' }]
    },
    doublevalid: false,
    doublevalid2: false,

  });

  onMounted(async () => { });

  // 打开弹窗
  const openDialog = async (row) => {
    console.log(row);

    state.isShowDialog = true;
    state.num = row.materielNum;
    state.TimeruleForm.ControlTime = row.inventoryDateTime;
    state.SaferuleForm.safeStock = row.quantityNeedCount;
    if (row.quantityNeedCount && row.inventoryDateTime) {
      state.isCheckedSafe = true;
      state.isChecked = true;
    } else if (row.quantityNeedCount && !row.inventoryDateTime) {
      state.isCheckedSafe = true;
      state.isChecked = false;
      state.TimeruleForm.ControlTime = "";
    } else if (!row.quantityNeedCount && row.inventoryDateTime) {
      state.isCheckedSafe = false;
      state.isChecked = true;
      state.SaferuleForm.safeStock = "";
    } else if (!row.quantityNeedCount && !row.inventoryDateTime) {
      state.isCheckedSafe = false;
      state.isChecked = false;
      state.SaferuleForm.safeStock = "";
      state.TimeruleForm.ControlTime = "";
    }
  };

  // 关闭弹窗
  const closeDialog = () => {
    //若想改变父组件的值，使用emit发射方法给父组件
    emits("handleQuery", true);
    state.isShowDialog = false;
  };
  const handleChangeSafe = (value) => {
    state.isCheckedSafe = value;
    console.log(state.isCheckedSafe);
    if (!state.isCheckedSafe) {
      state.SaferuleForm.safeStock = "";
      console.log("#" + state.SaferuleForm.safeStock);
    }
  };
  const handleChange = (value) => {
    state.isChecked = value;
    console.log(state.isChecked);
    // 如果是不设置的情况，就传给后端空字符串
    if (!state.isChecked) {
      state.TimeruleForm.ControlTime = "";
    }
  };
  const handleTab = (value) => {
    console.log(value);
    state.first = value.props.name;
  };
  // 提交

  const submit = () => {
    //'' null ''

    //如果没有设置安全库存，则把state.SaferuleForm.safeStock设置为Null
    if (state.isChecked && state.isCheckedSafe) {
      //验证tab框第一个的内容
      if (state.isChecked) {
        Timeref?.value.validate(async (valid, object) => {
          if (!valid) {
            console.log('校验不通过');
            state.doublevalid= false;
            ElMessage.error(object.ControlTime[0].message)
            return
          } else {
        await WmsApi()
              .PutTimeControl(state.num, state.TimeruleForm.ControlTime)
              .then(function (response) {
                state.doublevalid = true
                ElMessage.success("预警时间修改成功");
                if(state.doublevalid && state.doublevalid2){
        closeDialog();
      
      }
              })
              .catch(function (error) {
                console.log(error);
              });
          }

        });
      }
      //验证第二个tab框的内容
      if (state.isCheckedSafe) {
        Saferef?.value.validate(async (valid, object) => {
          if (!valid) {
            console.log('校验不通过');
            state.doublevalid2 = false;
            ElMessage.error(object.safeStock[0].message)
            return

          } else {

         await WmsApi()
              .PutSafeStorage(state.num, state.SaferuleForm.safeStock)
              .then(function (response) {
                state.doublevalid2 = true
                ElMessage.success("安全库存修改成功");

      if(state.doublevalid && state.doublevalid2){

        closeDialog();
      
      }
              })
              .catch(function (error) {
                console.log(error);
              });
          }

        });
      }
   //假如2个tab框都通过验证，则关闭窗口，但是会出现关闭延时的情况，
     
    } else if (state.isChecked && !state.isCheckedSafe) {

      WmsApi()
            .PutSafeStorage(state.num, state.SaferuleForm.safeStock )
            .then(function (response) {
              console.log(response);
              ElMessage.success("安全库存修改成功");
              closeDialog();
            
            })
            .catch(function (error) {
              console.log(error);
            });
      Timeref?.value.validate(async (valid, object) => {
        if (!valid) {
          console.log(object.ControlTime[0].message);
          ElMessage.error(object.ControlTime[0].message);
          return
        }
        else {
          WmsApi()
            .PutTimeControl(state.num, state.TimeruleForm.ControlTime)
            .then(function (response) {
              console.log(response);
              ElMessage.success("预警时间修改成功");
              closeDialog();
            
            })
            .catch(function (error) {
              console.log(error);
            })
            
        }

      });

    } else if (!state.isChecked && state.isCheckedSafe) {
      console.log("else");

      WmsApi()
            .PutTimeControl(state.num, state.TimeruleForm.ControlTime)
            .then(function (response) {
              console.log(response);
              ElMessage.success("预警时间修改成功");
              closeDialog();
            
            })
            .catch(function (error) {
              console.log(error);
            });
      Saferef?.value.validate(async (valid, object) => {
        if (!valid) {
          console.log('校验不通过');
          console.log(object.safeStock[0].message);
          ElMessage.error(object.safeStock[0].message)
          return

        } else {
          WmsApi()
            .PutSafeStorage(state.num, state.SaferuleForm.safeStock)
            .then(function (response) {
              console.log(response);
              ElMessage.success("安全库存修改成功");
              closeDialog();
            
            })
            .catch(function (error) {
              console.log(error);
            });
        }

      });

    } else if (!state.isChecked && !state.isCheckedSafe) {
      console.log("4");

      WmsApi()
        .PutTimeControl(state.num, state.TimeruleForm.ControlTime)
        .then(function (response) {
          console.log(response);
          ElMessage.success("预警时间修改成功");
          closeDialog();
        
        })
        .catch(function (error) {
          console.log(error);
        });

      WmsApi()
        .PutSafeStorage(state.num, state.SaferuleForm.safeStock)
        .then(function (response) {
          console.log(response);
          ElMessage.success("安全库存修改成功");
          closeDialog();
        
        })
        .catch(function (error) {
          console.log(error);
        });
    }
    
      
  };

  // 导出对象
  defineExpose({ openDialog });
</script>
<style lang="scss" scoped>
  .demo-tabs {
    height: 100px;
  }
</style>